//logs.js
const util = require('../../utils/util.js')
var api = require('../../config/api.js');
const app = getApp();
Page({
  data: {
    userInfo: {
      nickName: '点击登录',
      avatarUrl: '/resources/my01.png'
    },
    tempFilePaths: null,
    rank: 0,
    learnLen:0,
    hasLogin: false
  },
  onLoad: function () {
    let userInfo = wx.getStorageSync('userInfo');
    app.globalData.hasLogin = userInfo!=null
    this.setData({
      userInfo: userInfo,
      hasLogin: app.globalData.hasLogin
    })
  },

  onShow: function () {
    let userInfo = wx.getStorageSync('userInfo');
    console.log(this.data.userInfo, this.data.hasLogin, app.globalData.hasLogin);
    this.setData({
      userInfo: userInfo,
      hasLogin: app.globalData.hasLogin
    })
    console.log(this.data.userInfo, this.data.hasLogin, app.globalData.hasLogin);
    if (app.globalData.userInfo != null && userInfo != null) {
      this.getLearnData();
    }
  },

  clickTest(){
    let self = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        self.setData({
          tempFilePaths: res.tempFilePaths
        })
        util.uploadFile(api.upload, res.tempFilePaths[0])
        .then(res=>{
        })
      }
    })
  },

  wxLogin: function(e){
    let self = this;
    let userInfo = e.detail.userInfo;
    wx.login({
      success(res) {
        if (res.code) {
          util.request(api.AuthLoginByWeixin,{
            code: res.code,
            userInfo: userInfo
          }, 'POST').then(res =>{
            if (res.success){
              wx.setStorageSync('userInfo', res.data.userInfo);
              wx.setStorageSync('userToken', res.data.userToken);
              app.globalData.hasLogin = true
              self.setData({
                userInfo: res.data.userInfo,
                hasLogin: true
              });
              self.getLearnData();
            }
          }).catch(err =>{

          });

        } else {
          console.log('登录失败！')
        }
      }
    })
  },

  /*获取学习数据 */
  getLearnData(){
    let self = this;
    util.request(api.GetMyLearnData, {
    }, 'POST').then(res => {
      if (res.success) {
        self.setData({
          rank: res.data.rank,
          learnLen: res.data.learnLen,
        })
      }
    }).catch(err => {
    });
  },

  clickRank(){
    wx.navigateTo({
      url: '../../pages/my-rank/my-rank',
    })
  },

  test: function(){
    debugger
    wx.requestSubscribeMessage({
      tmplIds: ['ggVUb3Cb76E77EVf4eGxCc-JYnwTP8ilkqLCuh2I7JE'],
      success(res) {
        debugger
        util.request(api.Test, {
        }, 'POST').then(res => {

        }).catch(err => {

        });
      },
      fail(err) {
        debugger
      }
    });
  }
})
